package com.pl.lister;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.pl.entity.Student;
import com.pl.entity.SysUser;
import com.pl.service.StudentService;
import com.pl.service.SysUserService;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0
 * @Author 小胤
 * @Date 2024/4/25 20:07
 * @注释
 */
public class StudentReadLister extends AnalysisEventListener<Student> {
    //定义批量导入的时候 每次导入几条数据
    private static final int BATCH_COUNT=5;

    //用于存放临时的student数据
    private List<Student>studentList=new ArrayList<>();

    //引入service层
    private StudentService studentService;

    public StudentReadLister() {
    }

    public StudentReadLister(StudentService studentService) {
        this.studentService = studentService;
    }

    /**
     *  每读取一行 excel 都会回调此方法
     * @param student
     * @param analysisContext
     */
    @Override
    public void invoke(Student student, AnalysisContext analysisContext) {
        //先存一次
        studentList.add(student);
        if (studentList.size()>=BATCH_COUNT){
            saveData();
            studentList.clear();
        }
    }

    /**
     * 到读取表格完毕时 会回调此方法
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (studentList.size()>0){//最后一次导数据
            saveData();
            studentList.clear();
        }
    }
    /**
     * 批量导入
     */
    private void  saveData(){
        System.out.println("开始批量导入");
        studentService.addStudents(studentList);
        System.out.println("结束批量导入");

    }
}

